﻿using System.Text.RegularExpressions;
using System.Windows.Browser;

namespace Jacobi.Seesmic.FeedReader.Utilities
{
    /// <summary>
    /// Static helper class for text manipulation.
    /// </summary>
    internal static class TextHelper
    {
        /// <summary>
        /// Helper to strip out any xml or html tags and decode html encoding.
        /// </summary>
        /// <param name="text">The text to decode.</param>
        /// <returns>Never returns null.</returns>
        public static string DecodeText(string text)
        {
            // this strips xml/html tags from the text.
            var txt = Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
            // decodes html &..; tokens
            return HttpUtility.HtmlDecode(txt);
        }

        /// <summary>
        /// Helper to truncate text.
        /// </summary>
        /// <param name="text">The text to truncate.</param>
        /// <param name="maxLength">The maximum number of characters to return.</param>
        /// <returns>Returns the specified <paramref name="text"/> if it is shorter than the specified <paramref name="maxLength"/>.</returns>
        public static string TruncateText(string text, int maxLength)
        {
            if (text != null &&
                text.Length > maxLength)
            {
                text = text.Substring(0, maxLength);

                // find the last space
                int index = text.LastIndexOf(' ');
                text = text.Substring(0, index);

                text += " [...]";
            }

            return text;
        }
    }
}